//
//  HHPlayer.swift
//  HHSwift
//
//  Created by 华宏 on 2020/9/4.
//  Copyright © 2020 huahong. All rights reserved.
//

import UIKit
import AVFoundation

enum HHPlayState {
    case unKnown
    case playing
    case paused
    case failed
    case stoped
}


class HHPlayer:NSObject,HHPlayerProtocol {

    var observer:Any?
    
    typealias PlayProgressBlock = (_ currentTime:Float,_ totalTime:Float) -> Void
    typealias PlayEndBlock = () -> Void
    
    
    var  playProgressBlock:PlayProgressBlock?
    var  playEndBlock : PlayEndBlock?
    
    
    /// URL
    var assetURL:URL!
    
    /// 是否自动播放，默认YES
    var shouldAutoPlay:Bool = true

    
    var isPreparedToPlay:Bool = false
    
    /// 播放速率
    var rate:Float {
        get{
            return self.player.rate
        }
        
        set{
            self.player.rate = newValue
        }
    }
    
    var player:AVPlayer!
    var playerItem:AVPlayerItem!
//    var playerLayer:AVPlayerLayer!
    var container:PlayerView!
    
    var isPlaying:Bool = false
    var playStatus : HHPlayState = .unKnown
    
    private var playerLayer: AVPlayerLayer? {
        return self.container.playerLayer
    }
    
    
    /// 准备播放
    func prepareToPlay() {
        
        self.isPreparedToPlay = true
        let asset = AVURLAsset(url: self.assetURL)
        self.playerItem = AVPlayerItem(asset: asset)
        self.player = AVPlayer(playerItem: self.playerItem)
        self.playerLayer?.player = self.player
        
        addObserver()
    }
    
    func addObserver() {
        
        self.playerItem.addObserver(self, forKeyPath: "status", options: .new, context: nil)
        
        self.observer = self.player.addPeriodicTimeObserver(forInterval: CMTime(value: CMTimeValue(1.0), timescale: CMTimeScale(60.0)), queue: DispatchQueue.main) {[unowned self] (time:CMTime) in
            
            let duration:CMTime? = self.player.currentItem?.duration
            
            if let duration = duration {
//             let hasValidDuration = duration.isNumeric && newDuration.value != 0

                let totalTime = CMTimeGetSeconds(duration)
                let currentTime = CMTimeGetSeconds(time)
                if !currentTime.isNaN && !totalTime.isNaN {
                    self.playProgressBlock?(Float(currentTime),Float(totalTime))
                }
                
                
            }
            
        }
        
        NotificationCenter.default.addObserver(forName: Notification.Name.AVPlayerItemDidPlayToEndTime, object:nil, queue: OperationQueue.main) { (Notification) in
            
              self.playEndBlock?()
           }
    }
    
    ///播放
    func play() {
        if isPreparedToPlay == true {
            self.player.play()
            self.isPlaying = true
            self.playStatus = .playing
            
        }else{
            prepareToPlay()
        }
    }
    

    /// 重新加载播放器
    func reloadPlayer() {
           
    }
    

    ///暂停
    func pause() {
        if self.player != nil && self.player.rate > 0 {
            self.player.pause()
            self.playStatus = .paused
            self.isPlaying = false
            self.playerItem.cancelPendingSeeks()
        }
    }
   

    ///停止
    func stop() {
      
        pause()
        
    }
    

    /// 重新播放
    func replay() {
              
    }
  
    func seek(to time: Float, completionHandler: @escaping (Bool) -> Void) {
        
        let newTime = CMTimeMakeWithSeconds(Float64(time), preferredTimescale: 60)
        self.player.seek(to: newTime, completionHandler: completionHandler)
    }
    
//MARK: - KVO
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "status" {
            
            
            if let newKey = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
                
                let status = AVPlayerItem.Status(rawValue: newKey.intValue)!
               if status == .readyToPlay && self.shouldAutoPlay == true {
                  play()
               }
            }
           
            
        }
    }

    deinit {
        
       self.playerItem.removeObserver(self, forKeyPath: "status")
        
        //移除该控制器下的所有通知
        NotificationCenter.default.removeObserver(self)
        
  //移除AVPlayerItemDidPlayToEndTime单个通知
//        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
    }
}
